import jsPDF from "jspdf";
import html2canvas from "html2canvas";

const htmlToPdf = {
  async getPdf(title, id) {
    try {
      const element = document.querySelector(id);
      const pages = element.querySelectorAll('.pdf-page');
      const pdf = new jsPDF('p', 'pt', 'a4');
      
      // 等待所有页面渲染完成
      let isFirstPage = true;
      
      const promises = Array.from(pages).map(async (page, index) => {
        const canvas = await html2canvas(page, {
          allowTaint: true,
          useCORS: true,
          logging: false,
          scale: 2.5,
          backgroundColor: '#ffffff'
        });

        // 将canvas转为图片，使用PNG格式保持更好的质量
        const imgData = canvas.toDataURL('image/png', 1.0);
        
        // 计算合适的尺寸，保持宽高比但充满宽度
        const pdfWidth = 595.28;
        const pdfHeight = 841.89;
        const canvasRatio = canvas.width / canvas.height;
        
        // 以PDF宽度为准，按比例计算高度
        const finalWidth = pdfWidth;
        const finalHeight = pdfWidth / canvasRatio;
        const x = 0;
        const y = 0;
        
        // 如果内容高度超过PDF页面高度，需要分页处理
        if (finalHeight > pdfHeight) {
          // 计算需要多少页
          const pageCount = Math.ceil(finalHeight / pdfHeight);
          
          for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
            if (!isFirstPage) {
              pdf.addPage();
            }
            isFirstPage = false;
            
            // 计算当前页的裁剪区域
            const sourceY = (pageIndex * pdfHeight / finalHeight) * canvas.height;
            const sourceHeight = Math.min((pdfHeight / finalHeight) * canvas.height, canvas.height - sourceY);
            
            // 创建裁剪后的canvas
            const tempCanvas = document.createElement('canvas');
            const tempCtx = tempCanvas.getContext('2d');
            tempCanvas.width = canvas.width;
            tempCanvas.height = sourceHeight;
            
            tempCtx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight);
            
            const pageImgData = tempCanvas.toDataURL('image/png', 1.0);
            const pageHeight = Math.min(pdfHeight, finalHeight - pageIndex * pdfHeight);
            
            pdf.addImage(
              pageImgData,
              'PNG',
              x,
              y,
              finalWidth,
              pageHeight,
              '',
              'SLOW'
            );
          }
        } else {
          // 内容高度不超过页面，直接添加
          if (!isFirstPage) {
            pdf.addPage();
          }
          isFirstPage = false;
          
          pdf.addImage(
            imgData,
            'PNG',
            x,
            y,
            finalWidth,
            finalHeight,
            '',
            'SLOW'
          );
        }

        return true;
      });

      // 等待所有页面处理完成后保存
     // 等待所有页面处理完成后保存
     await Promise.all(promises);
      
     // 如果传入了title，就保存文件
    //  if (title) {
    //    pdf.save(title + '.pdf');
    //  }
     
     // 返回blob数据
     return pdf.output('blob');

    } catch (error) {
      console.error('PDF生成错误:', error);
    }
  }
};

export default htmlToPdf;

